package com.yanghui.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yanghui.annotation.SystemLog;
import com.yanghui.pojo.Blog;
import com.yanghui.pojo.BlogStatus;
import com.yanghui.service.BlogService;
import com.yanghui.utils.ConstantUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author YH
 */
@Controller
@RequestMapping("/admin")
public class BlogControllerAdmin {

    @Resource(name = "blogServiceImpl")
    private BlogService blogService;


    /**
     * 按照不同时间查询博客的发表数量
     */
    @RequestMapping(value = "/selectBlogByDate", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> selectBlogListByDate(
            @RequestParam(value = "status") String status,
            @RequestParam(value = "startTime") String startTime,
            @RequestParam(value = "endTime") String endTime)
            throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (status != "" && status != null) {
            map.put("status", status);
        }
        if (startTime != "" && startTime != null) {
            map.put("startTime", startTime);
        }
        if (endTime != "" && endTime != null) {
            map.put("endTime", endTime);
        }

        List<?> list = blogService.selectBlogByDate(map);
        Map<String, Object> returnMap = new HashMap<>();
        if (list.size() > 0) {
            returnMap.put("status", 200);
        } else {
            // 500表示：返回值为Null
            returnMap.put("status", 500);
        }
        returnMap.put("list", list);

        return returnMap;
    }

    /**
     * 按照博客点击量降序
     * 取出前几条数据
     * id,clickNum
     * 可以通过id查看对应的博客信息
     */
    @RequestMapping("/selectBlogByClick")
    @ResponseBody
    public Map<String,Object> selectBlogByClick() {
        Map<String,Object> map = new HashMap<>();
        List<?> list = blogService.selectBlogByClick();

        if (list.size() > 0) {
            map.put("status", 200);
        } else {
            map.put("status", 500);
        }
        map.put("list", list);

        return map;
    }

    /**
     * 按照指定日期查询博客数量
     */
    @RequestMapping("/selectBlogListByDate")
    @ResponseBody
    public Map selectBlogListByDate(
            @RequestParam("status") Integer status,
            @RequestParam("startTime") String startTime,
            @RequestParam("endTime") String endTime) {
        Map<String,Object> map = new HashMap<>();

        try {
            Date start = new SimpleDateFormat("yyyy-MM-dd").parse(startTime);
            Date end = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
            map.put("status", status);
            map.put("startTime", start);
            map.put("endTime", end);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Map<Object,Object> resultMap = blogService.selectBlogListByDate(map);

        return resultMap;
    }

    /**
     * 按博客状态查询博客数量
     */
    @RequestMapping("/selectBlogListByStatus")
    @ResponseBody
    public Map selectBlogListByStatus() {
        Map<String,Object> map = new HashMap<>();
        List<?> list = blogService.selectBlogListByStatus();

        if (list.size() > 0) {
            map.put("status", 200);
        } else {
            map.put("status", 500);
        }

        map.put("list", list);
        return map;
    }

    /**
     * 更新博客
     */
    @RequestMapping("/updateBlog")
    @ResponseBody
    @SystemLog(description = ConstantUtil.BLOG_UPDATE, userType = ConstantUtil.USER_TYPE_ADMIN)
    public Map updateBlog(@RequestParam("param") String param,
                          Blog blog) {
        /** 受影响记录行数 */
        int count = blogService.updateBlog(blog);

        Map<String,Object> map = new HashMap<>();
        /** 更新成功 */
        if (count == 1) {
            map.put("status", 200);
        /** 更新失败 */
        } else {
            map.put("status", 500);
        }

        return map;
    }

    /**
     * 按照博客id查询对应的博客
     */
    @RequestMapping("/selectBlogById")
    @ResponseBody
    public Map selectBlogById(@RequestParam("id") Integer id) {
        Map map = new HashMap();
        Blog blog = blogService.selectBlogById(id);

        /** 如果查询到了对应的博客 */
        if (blog != null) {
            map.put("status", 200);
         /** 如果没有查询到对应的博客 */
        } else {
            map.put("status", 500);
        }

        map.put("blog", blog);

        return map;
    }

    /**
     * 按照给定的条件查询博客
     * 如标题、关键字、博客状态条件
     * 以及是否按照某个字段进行排序
     */
    @RequestMapping("/selectGroupLikeBlogListByPage")
    @ResponseBody
    public Map selectGroupLikeBlogListByPage(
            Blog blog,
            @RequestParam(value = "page", required = true, defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "sort", required = true, defaultValue = "addTime") String sort
    ) {
        /** 把要查询的条件封装到 Map 中 */
        Map<String,Object> map = new HashMap<>();
        map.put("sort", sort);
        if (blog.getTitle() != null && "".equals(blog.getTitle()) != true) {
            map.put("title", blog.getTitle());
        }
        if (blog.getKeyword() != null && "".equals(blog.getKeyword()) != true) {
            map.put("keyword", blog.getKeyword());
        }
        if (blog.getStatus() != null && "".equals(blog.getStatus()) != true) {
            map.put("status", blog.getStatus());
        }
        if (blog.getIsRecommend() != null) {
            map.put("recommend", blog.getIsRecommend());
        }
        if (blog.getIsTop() != null) {
            map.put("isTop", blog.getIsTop());
        }

        /** 使用PageHelper插件将结果进行封装分页 */
        PageHelper.startPage(page, pageSize);
        List<Blog> blogList = blogService.selectGroupLikeBlogListByPage(map);
        PageInfo pageInfo = new PageInfo(blogList,5);
        Map<String,Object> resultMap = new HashMap<>();

        /** 如果查询到了对应的博客，封装成功状态码 200 */
        if (blogList.size() > 0) {
            resultMap.put("status", 200);
        /** 没有查询到对应的博客，封装失败状态码 500 */
        } else {
            resultMap.put("status", 500);
        }

        resultMap.put("blogList", blogList);
        resultMap.put("pageInfo", pageInfo);

        return resultMap;
    }

    /**
     * 实现添加博客功能
     * 同时需要把对应的博客类别的数量更新
     */
    @RequestMapping("/addBlog")
    @ResponseBody
    @SystemLog(description = ConstantUtil.BLOG_ADD, userType = ConstantUtil.USER_TYPE_ADMIN)
    public Map addBlog(@RequestParam("param") String param,
                       Blog blog) {
        Map<String,Object> map = new HashMap<>();
        /** 把博客关键字中的所有英文逗号替换为中文逗号 */
        blog.setKeyword(blog.getKeyword().replace(",", "，"));
        /** 返回受影响记录的行数 */
        int count = blogService.addBlog(blog);
        /** 插入成功，返回成功状态码 */
        if (count == 1) {
            map.put("status", 200);
        /** 插入失败，返回失败状态码 */
        } else {
            map.put("status", 500);
        }
        return map;
    }

    /**
     * 按照博客状态查询博客的数量
     * 三种状态：
     * 草稿（-1）、已经发表（1）、回收站（2）
     * @return
     */
    @RequestMapping(value = "/selectBlogCountByStatus")
    @ResponseBody
    public Map<String,Object> selectBlogCountByStatus() {
        Map<String,Object> map = new HashMap<>();
        List<BlogStatus> countList = blogService.selectBlogCountByStatus();
        /** 查询成功 */
        if (countList.size() > 0) {
            map.put("status", 200);
        } else {
            map.put("status", 500);
        }
        map.put("countList", countList);
        return map;
    }


    /**
     * 整合summernote实现图片上传
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadBlogImages")
    @ResponseBody
    public Map<String, Object> uploadBlogImage(HttpServletRequest request)
            throws Exception {
        CommonsMultipartResolver multipartResolver =
                new CommonsMultipartResolver(request.getSession().getServletContext());

        Map<String, Object> map = new HashMap<>();
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
            Iterator<String> fileNamesIter = mreq.getFileNames();
            while (fileNamesIter.hasNext()) {
                MultipartFile file = mreq.getFile(fileNamesIter.next());
                if (file != null) {
                    String myFileName = file.getOriginalFilename();
                    if (myFileName.trim() != "") {
                        String fileName = file.getOriginalFilename();
                        String fileBaseName = fileName.substring(0, fileName.lastIndexOf("."));
                        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        String newFileName = df.format(new Date());
                        String fileNames = newFileName + new Random().nextInt(1000000) + "." + fileExt;
                        String filePath = "D:" + File.separator + "upload" + File.separator
                                + "blog" + File.separator + newFileName + File.separator + fileNames;

                        File localFile = new File(filePath);
                        if (!localFile.exists()) {
                            localFile.mkdirs();
                        }
                        file.transferTo(localFile);
                        fileNames = "/upload/blog/" + newFileName + "/" + fileNames;

                        map.put("name", fileBaseName);
                        map.put("path", fileNames);
                        map.put("status", 200);
                    }
                }
            }
        }
        return map;
    }

    /**
     * 上传封面图片
     *
     */
    @RequestMapping(value = "/uploadBg", method = RequestMethod.POST)
    @ResponseBody
    @SystemLog(description = ConstantUtil.UPLOAD_IMAGES, userType = ConstantUtil.USER_TYPE_ADMIN)
    public Map<String, Object> uploadBg(HttpServletRequest request) throws Exception {
        CommonsMultipartResolver multipartResolver =
                new CommonsMultipartResolver(request.getSession().getServletContext());
        Map<String, Object> map = new HashMap<>();
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
            Iterator<String> fileNamesIter = mreq.getFileNames();
            while (fileNamesIter.hasNext()) {
                MultipartFile file = mreq.getFile(fileNamesIter.next());
                if (file != null) {
                    String myFileName = file.getOriginalFilename();
                    if (myFileName.trim() != "") {
                        String fileName = file.getOriginalFilename();
                        String fileBaseName = fileName.substring(0, fileName.lastIndexOf("."));
                        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        String newFileName = df.format(new Date());
                        String fileNames = newFileName + new Random().nextInt(1000000) + "." + fileExt;
                        String filePath = "D:" + File.separator + "upload" + File.separator
                                + "background" + File.separator + fileNames;
                        File localFile = new File(filePath);
                        if (!localFile.exists()) {
                            localFile.mkdirs();
                        }
                        file.transferTo(localFile);
                        fileNames = "/upload/background/" + newFileName + "/" + fileNames;
                        map.put("name", fileBaseName);
                        map.put("path", fileNames);
                        map.put("status", 200);
                    }
                }
            }
        }

        return map;
    }


    /**
     * 文件上传
     */
    @RequestMapping("/uploadFile")
    public void upload(@RequestParam(value = "username", required = false) String username,
                         @RequestParam(value = "headerImg")MultipartFile file) {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());

        /** 文件保存 */
        try {
            file.transferTo(new File("D:" + File.separator + "upload" + File.separator + "background"
                    + File.separator + file.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
